import styles from '../index.module.less'

import { Card, Form, Input, Button, message } from 'antd'

import { addHosParamesType } from '@/api/hospitalSet/model/hospitalSetTypes'
import { addHosRequest, queryHosByIdRequest, updateHosRequest } from '@/api/hospitalSet'
import { useNavigate, useParams } from 'react-router-dom'
import { useEffect } from 'react'

export default function AddOrUpdateHospital() {

  const navigate = useNavigate()

  const [form] = Form.useForm()

  const { id } = useParams()

  const addHosFinishHandler = async (values: addHosParamesType) => {
    try {
      if (id) {
        await updateHosRequest({
          ...values,
          id
        })
        message.success('修改成功')
      } else {
        await addHosRequest(values)
        message.success('添加成功')
      }
      // 跳转医院设置页
      navigate('/syt/hospital/hospitalSet')
    } catch (error: any) {
      message.error(error.message)
    }
  }

  const goBack = () => {
    navigate(-1)
  }

  useEffect(() => {
    const queryHosById = async () => {
      if(id) {
        const result = await queryHosByIdRequest(id)
        form.setFieldsValue(result)
      }
    }
    queryHosById()
  }, [])

  return (
    <Card>
      <Form
      form={form}
      name="basic"
      labelCol={{ span: 3 }}
      wrapperCol={{ span: 18 }}
      onFinish={addHosFinishHandler}
    >
      <Form.Item
        label="医院名称"
        name="hosname"
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="医院编号"
        name="hoscode"
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="api基础路径"
        name="apiUrl"
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="联系人姓名"
        name="contactsName"
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="联系人手机"
        name="contactsPhone"
      >
        <Input />
      </Form.Item>

      <Form.Item wrapperCol={{ offset: 3 }}>
        <Button type="primary" htmlType="submit" className={styles.mr}>
          提交
        </Button>
        <Button type="default" htmlType="button" onClick={goBack}>
          返回
        </Button>
      </Form.Item>
    </Form>
    </Card>
  )
}
